package com.pri.chat;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.location.AMapLocation;
import com.google.gson.Gson;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.common.ToastHelper;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.DTBean;
import com.netease.nim.uikit.net.entity.IndexInfoBean;
import com.netease.nim.uikit.net.entity.WishListBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.netease.nim.uikit.support.permission.MPermission;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionDenied;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionGranted;
import com.netease.nim.uikit.support.permission.annotation.OnMPermissionNeverAskAgain;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.StatusCode;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.AuthServiceObserver;
import com.netease.nimlib.sdk.msg.MsgService;
import com.pri.chat.activity.LoginActivity;
import com.pri.chat.activity.ReleaseDTActivity;
import com.pri.chat.activity.WalletActivity;
import com.pri.chat.application.APP;
import com.pri.chat.bean.KeyAndValueEntity;
import com.pri.chat.database.greendao.KeyAndValueEntityDao;
import com.pri.chat.fragment.MainFragment;
import com.pri.chat.fragment.PersonCenterFragment;
import com.pri.chat.fragment.RecentContactsFragment;
import com.pri.chat.fragment.VideoFragment1;
import com.pri.chat.fragment.WishFragment;
import com.pri.chat.nim.session.SessionHelper;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.GpsUtil;
import com.pri.chat.utils.LocationUtil;
import com.pri.chat.utils.NotificationUtil;
import com.pri.chat.utils.StringUtils;
import com.pri.chat.utils.TimeUtils;
import com.pri.chat.utils.gps.GPSLocationListener;
import com.pri.chat.utils.gps.GPSLocationManager;
import com.pri.chat.utils.gps.GPSProviderStatus;
import com.pri.chat.view.XRadioGroup;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.NoticeDialogRedSure;
import com.vondear.rxui.view.dialog.RxDialogRedSure;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.vondear.rxtool.RxActivityTool.skipActivity;


public class MainActivity extends AppCompatActivity implements XRadioGroup.OnCheckedChangeListener {
    private void requestBasicPermission() {
        MPermission.with(MainActivity.this).setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_PERMISSIONS).request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {

    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        ToastHelper.showToast(this, "部分权限开启失败，可能会影响操作");
    }

    /**
     * 基本权限管理
     */
    private final int BASIC_PERMISSION_REQUEST_CODE = 110;
    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            android.Manifest.permission.ACCESS_FINE_LOCATION,
            android.Manifest.permission.ACCESS_COARSE_LOCATION
    };
    public static AlertDialog mLoginAlert;
    public static AlertDialog.Builder mLoginBuider;
    FragmentTransaction fTransaction;
    @BindView(R.id.ly_content)
    FrameLayout lyContent;
    @BindView(R.id.btn_main)
    RadioButton btnMain;
//    @BindView(R.id.btn_video)
//    RadioButton btnVideo;

    @BindView(R.id.unread_num)
    TextView unread_num;
    @BindView(R.id.btn_message)
    RadioButton btnMessage;

    @BindView(R.id.btn_shop)
    RadioButton btnShop;
    @BindView(R.id.btn_me)
    RadioButton btnMe;
    @BindView(R.id.rg_tab_bar)
    XRadioGroup rgTabBar;
    @BindView(R.id.lines)
    View lines;

    @BindView(R.id.btn_main1)
    TextView btnMain1;
//    @BindView(R.id.btn_video1)
//    TextView btnVideo1;
    @BindView(R.id.btn_message1)
    TextView btnMessage1;
    @BindView(R.id.btn_shop1)
    TextView btnShop1;
    @BindView(R.id.btn_me1)
    TextView btnMe1;

    @BindView(R.id.rg_tab_bar1)
    LinearLayout rgTabBar1;
    private FragmentManager fManager;
    private Fragment fg1;
//    private Fragment fg2;
    private Fragment fg3;
    private Fragment fg4;
    private Fragment fg5;
    //退出时的时间
    private long mExitTime;
    private int systemNum = 0;

    private MyReceiver myReceiver;
    private boolean isError = false;
    public static final String UPDATE_DACALL = "UPDATE_DACALL";
    public static final String UPDATE_DONGTAI = "UPDATE_DONGTAI";
    public static final String UPDATE_WISH = "UPDATE_WISH";
    public static final String DELETE_WISH = "DELETE_WISH";
    public static final String DELETE_DONGTAI = "DELETE_DONGTAI";
    public static final String DELETE_VEDIO = "DELETE_VEDIO";
    public static final String UPDATE_VEDIO = "UPDATE_VEDIO";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_layout);
        APP.getInstance().add(this);
        ButterKnife.bind(this);
        initFragments(savedInstanceState != null);
        initView();
        IntentFilter filter = new IntentFilter();
        filter.addAction(UPDATE_DACALL);
        filter.addAction(UPDATE_DONGTAI);
        filter.addAction(UPDATE_WISH);
        filter.addAction(DELETE_WISH);
        filter.addAction(DELETE_DONGTAI);
        filter.addAction(DELETE_VEDIO);
        filter.addAction(UPDATE_VEDIO);
        initNim(this);
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, filter);

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        mHandle.sendEmptyMessage(0);
                        Thread.sleep(30000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public Handler mHandle = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            heartConnect();
        }
    };

    /**
     * 未登录弹窗
     *
     * @param activity activity
     */
    public static void showLoginDialog(Activity activity) {
        mLoginAlert = null;
        mLoginBuider = new AlertDialog.Builder(activity);
        mLoginAlert = mLoginBuider.setIcon(R.mipmap.logo)
                .setTitle(R.string.main_tip)
                .setMessage(R.string.main_no_login)
                .setNegativeButton(R.string.cancer, (dialog, which) -> mLoginAlert.dismiss())
                .setPositiveButton(R.string.confirm, (dialog, which) -> {
                    mLoginAlert.dismiss();
                    Intent intent = new Intent();
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                    intent.setClass(activity, LoginActivity.class);
                    activity.startActivityForResult(intent, 1);
                })
                .create();             //创建AlertDialog对象
        mLoginAlert.show();                    //显示对话框
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }


    //对返回键进行监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出到后台
     */
    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(MainActivity.this, "再按一次进入后台", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            Intent i = new Intent(Intent.ACTION_MAIN);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addCategory(Intent.CATEGORY_HOME);
            startActivity(i);
        }
    }

    @OnClick({R.id.btn_main1, R.id.btn_message1, R.id.btn_shop1, R.id.btn_me1})
    public void onViewClicked(View v) {
        rgTabBar.setVisibility(View.VISIBLE);
        lines.setVisibility(View.VISIBLE);
        rgTabBar1.setVisibility(View.GONE);
//        if (v.getId() == R.id.btn_main1) {
//            btnMain.setChecked(true);
//        } else if (v.getId() == R.id.btn_message1) {
//            btnMessage.setChecked(true);
//        } else if (v.getId() == R.id.btn_shop1) {
//            btnShop.setChecked(true);
//        } else {
//            btnMe.setChecked(true);
//        }
    }


    private int checkid;

    @Override
    public void onCheckedChanged(XRadioGroup group, @IdRes int checkedId) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        System.out.println(getSupportFragmentManager().getFragments().size() + "个fragment");
        hideAllFragment(ft);
        for (Fragment f : getSupportFragmentManager().getFragments()) {
            if (TextUtils.equals(f.getTag(), String.valueOf(checkedId))) {
                /*if(f instanceof WishFragment){
                    ((WishFragment)f).getWishMoney();
                }*/
                ft.show(f);
                break;
            }
        }
        ft.commitAllowingStateLoss();
    }

    //隐藏所有Fragment
    private void hideAllFragment(FragmentTransaction fragmentTransaction) {
        if (fg1 != null) fragmentTransaction.hide(fg1);
//        if (fg2 != null) fragmentTransaction.hide(fg2);
        if (fg3 != null) fragmentTransaction.hide(fg3);
        if (fg4 != null) fragmentTransaction.hide(fg4);
        if (fg5 != null) fragmentTransaction.hide(fg5);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode){
            case 887:
                //开启GPS，重新添加地理监听
                initLoc();
                break;
            default:break;
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    /**
     * 当前应用是否处于前台
     *
     * @param context 上下文
     * @return 是否处于前台
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private boolean isForeground(Context context) {
        if (context != null) {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
            String currentPackageName = cn.getPackageName();
            if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(context.getPackageName())) {
                return true;
            }
            return false;
        }
        return false;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(myReceiver);
    }

    /**
     * 获取APP版本号
     * @param ctx 上下文
     * @return 版本名称
     */
    public static int getAPPVersionCode(Context ctx) {
        int currentVersionCode = 0;
        String appVersionName = "";
        PackageManager manager = ctx.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(ctx.getPackageName(), 0);
            appVersionName = info.versionName; // 版本名
            currentVersionCode = info.versionCode; // 版本号
            System.out.println(currentVersionCode + " " + appVersionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return currentVersionCode;
    }


    private AlertDialog mUpdateAlert;
    private AlertDialog.Builder mUpdateBuidler;

    /**
     * 更新应用弹窗
     *
     * @param activity 上下文
     * @param s        提示文字
     */
    public void showVersionDialog(Activity activity, String s) {
        mUpdateAlert = null;
        mUpdateBuidler = new AlertDialog.Builder(activity);
        mUpdateAlert = mUpdateBuidler
                .setTitle(R.string.main_tip)
                .setMessage(R.string.jump_app_store)
                .setCancelable(false)
                .setPositiveButton(R.string.confirm, (dialog, which) -> openBrowser(activity, s))
                .create();             //创建AlertDialog对象
        mUpdateAlert.show();                    //显示对话框
    }

    /**
     * 打开浏览器
     *
     * @param context 上下文
     * @param url     链接
     */
    public static void openBrowser(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        // 注意此处的判断intent.resolveActivity()可以返回显示该Intent的Activity对应的组件名
        // 官方解释 : Name of the component implementing an activity that can display the intent
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            context.startActivity(Intent.createChooser(intent, context.getString(R.string.choice_browser)));
        } else {
            RxToast.normal("链接错误或无浏览器");
        }
    }

    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (UPDATE_DACALL.equals(intent.getAction())) {
                //更新动态
                String memberId = intent.getExtras().getString("memberId");
                int sfdc = intent.getExtras().getInt("sfdc");
                updateDaCall(memberId, sfdc);
            } else if (UPDATE_DONGTAI.equals(intent.getAction())) {
                DTBean dtBean = intent.getExtras().getParcelable("dtObj");
                updateDongTai(dtBean);
            } else if (UPDATE_WISH.equals(intent.getAction())) {
                WishListBean wishObj = intent.getExtras().getParcelable("wishObj");
                if (fg1 != null) {
                    ((WishFragment) fg1).updateWish(wishObj);
                }
            } else if (DELETE_WISH.equals(intent.getAction())) {
                WishListBean wishObj = intent.getExtras().getParcelable("wishObj");
                if (fg1 != null) {
                    ((WishFragment) fg1).deteleWish(wishObj);
                }
            } else if (DELETE_DONGTAI.equals(intent.getAction())) {
                DTBean dtBean = intent.getExtras().getParcelable("dtObj");
                if (fg4 != null) {
                    ((MainFragment) fg4).deleteDongTai(dtBean);
                }
            }
//            else if (DELETE_VEDIO.equals(intent.getAction())) {
//                DTBean dtBean = intent.getExtras().getParcelable("dtObj");
//                if (fg2 != null) {
//                    ((VideoFragment1) fg2).deleteVedio(dtBean);
//                }
//            }
//            if (UPDATE_VEDIO.equals(intent.getAction())) {
//                DTBean dtBean = intent.getExtras().getParcelable("dtObj");
//                if (fg2 != null) {
//                    ((VideoFragment1) fg2).updateVedio(dtBean);
//                }
//            }
        }
    }

    public void updateDaCall(String memberId, int sfdc) {
        if (fg4 != null) {
            ((MainFragment) fg4).updateDaCall(memberId, sfdc);
        }
    }

    public void updateDongTai(DTBean dtBean) {
        if (fg4 != null) {
            ((MainFragment) fg4).updateDongTai(dtBean);
        }
    }

    private String pathDirs = Environment.getExternalStorageDirectory() + "/com.pri.chat/cache/video/";

    private void deleteVedio() {
        File pathFile = new File(pathDirs);
        File[] files = pathFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            files[i].delete();
        }
        SharedHelper.saveKeyValueForString(this, "deleteTime", TimeUtils.getCurrentTime());
    }

    private void initNim(Context context) {
        NIMClient.getService(AuthServiceObserver.class).observeOnlineStatus(
                new Observer<StatusCode>() {
                    public void onEvent(StatusCode status) {
                        if (status.wontAutoLogin()) {
                            SharedHelper.clear(context);
                            SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
                            sp.edit().putBoolean("isFirst", true).apply();
                            APP.getInstance().finishAllActivity();
                            RxToast.normal("您的账号已经在别的手机端登录！");
                            NIMClient.getService(AuthService.class).logout();
                            skipActivity(context, LoginActivity.class);
                            finish();
                        }
                    }
                }, true);

    }

    private void initFragments(boolean clearInfo) {
        fTransaction = getSupportFragmentManager().beginTransaction();
        if (clearInfo) {
            for (Fragment f : getSupportFragmentManager().getFragments()) {
                fTransaction.remove(f);
            }
        }
        fg1 = new WishFragment();
//        fg2 = new VideoFragment1();
        fg3 = new RecentContactsFragment();
        fg4 = new MainFragment();
        fg5 = new PersonCenterFragment();
        fTransaction
                .add(R.id.ly_content, fg4, String.valueOf(R.id.btn_main))
//                .add(R.id.ly_content, fg2, String.valueOf(R.id.btn_video))
                .add(R.id.ly_content, fg3, String.valueOf(R.id.btn_message))
                .add(R.id.ly_content, fg1, String.valueOf(R.id.btn_shop))
                .add(R.id.ly_content, fg5, String.valueOf(R.id.btn_me))
                .commitNow();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if(GpsUtil.isOPen(this)){
            initLoc();
        }else{
//            RxToast.normal("请打开GPS");
//            GpsUtil.openGPS(this);
        }
    }

    public void saveLocationInfo(Location location) {
        System.out.println("-----------222222222");
        SharedHelper.saveKeyValueForString(this, "lng", location.getLongitude() + "");
        SharedHelper.saveKeyValueForString(this, "lat", location.getLatitude() + "");
        SharedHelper.saveKeyValueForString(this, "locationTime", System.currentTimeMillis() + "");

        List<Address> addList = null;
        Geocoder ge = new Geocoder(getApplicationContext());
        try {
            addList = ge.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (addList != null && addList.size() > 0) {
            for (int i = 0; i < addList.size(); i++) {
                Address ad = addList.get(i);

                List<KeyAndValueEntity> kList = APP.getKeyAndValueEntityDao().queryBuilder().where(KeyAndValueEntityDao.Properties.TypeKey.eq("LocationCity")).build().list();
                KeyAndValueEntity city;
                if(kList != null && kList.size() > 0){
                    city = kList.get(0);
                }else{
                    city = new KeyAndValueEntity();
                    city.setTypeKey("LocationCity");
                }
                city.setValue(ad.getLocality());
                APP.getKeyAndValueEntityDao().save(city);

                SharedHelper.saveKeyValueForString(this, "province", ad.getAdminArea());
                SharedHelper.saveKeyValueForString(this, "city", ad.getLocality());
                SharedHelper.saveKeyValueForString(this, "area", ad.getSubLocality());
                break;
            }
        }
    }

    private void initView() {
        SessionHelper.init();
        fManager = getSupportFragmentManager();
        rgTabBar.setOnCheckedChangeListener(this);
        //获取第一个单选按钮，并设置其为选中状态
        btnShop.setChecked(true);
        requestBasicPermission();
        //通知权限判断
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //判断是否需要开启通知栏功能
            NotificationUtil.OpenNotificationSetting(this, new NotificationUtil.OnNextLitener() {
                @Override
                public void onNext(int type) {
                    //获取版本信息
//                    getIndexInfo();
                }
            });
        }
        //获取红包信息
//        initGPS();
        showRedDialog();
        showNoticeDialogSure();
        getIndexInfo();
    }



    private String noticeContent = null;
    /**
     * 获取首頁信息
     */
    private void getIndexInfo() {
        SubscriberOnNextListener<BaseBean<IndexInfoBean>> onNextListener = baseBean -> {
            if (baseBean.getData().getVersion() != null) {
                showVersionDialog(MainActivity.this, baseBean.getData().getVersion().getApkPath());
            }else{
                String show = SharedHelper.readValueByKeyForString(this,"show");
                String hongbao = SharedHelper.readValueByKeyForString(this,"hongbao");
                if(!"1".equals(show)) {
                    rxDialogRedSure.getmTvPrice().setText(hongbao+"元红包");
                    rxDialogRedSure.show();
                    SharedHelper.saveKeyValueForString(this,"show","1");
                    noticeContent = baseBean.getData().getNoticeMsg();
                }else{
                    if(!StringUtils.isEmpty(baseBean.getData().getNoticeMsg())){
                        //通知提示框
                        noticeContent = baseBean.getData().getNoticeMsg();
                        noticeDialogSure.getTextContent().setText(noticeContent);
                        noticeDialogSure.show();
                    }
                }
            }

            List<KeyAndValueEntity> kavList = APP.getKeyAndValueEntityDao().queryBuilder().where(KeyAndValueEntityDao.Properties.TypeKey.eq("unreadnum")).build().list();
            KeyAndValueEntity kavObj = kavList.get(0);
            kavObj.setValue(new Gson().toJson(baseBean.getData().getMsgInfo()));
            APP.getKeyAndValueEntityDao().save(kavObj);
            int totalNum = baseBean.getData().getMsgInfo().getGzNum()+baseBean.getData().getMsgInfo().getPlNum()+baseBean.getData().getMsgInfo().getZanNum()+baseBean.getData().getMsgInfo().getWishNum()+baseBean.getData().getMsgInfo().getXttzNum();
            int unreadNum = NIMClient.getService(MsgService.class).getTotalUnreadCount();
            if(totalNum + unreadNum > 0){
                unread_num.setText((totalNum + unreadNum)+"");
                unread_num.setVisibility(View.VISIBLE);
            }
        };
        Map<String, Object> params = new HashMap<>();//登录上传参数
        params.put("versionCode", getAPPVersionCode(this));
        params.put("memberId", SharedHelper.readId(this));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().getIndexInfo(new ProgressSubscriber<>(onNextListener, this, false),requestBody);
    }

    RxDialogRedSure rxDialogRedSure;
    private void showRedDialog() {
        rxDialogRedSure = new RxDialogRedSure(this);
        rxDialogRedSure.getmTvGo().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rxDialogRedSure.dismiss();
                skipActivity(MainActivity.this, WalletActivity.class);
                if(!StringUtils.isEmpty(noticeContent)){
                    noticeDialogSure.getTextContent().setText(noticeContent);
                    noticeDialogSure.show();
                }
            }
        });
        rxDialogRedSure.getRlBG().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rxDialogRedSure.dismiss();
                if(!StringUtils.isEmpty(noticeContent)){
                    noticeDialogSure.getTextContent().setText(noticeContent);
                    noticeDialogSure.show();
                }
            }
        });
    }


    NoticeDialogRedSure noticeDialogSure;

    private void showNoticeDialogSure() {
        noticeDialogSure = new NoticeDialogRedSure(this);
        noticeDialogSure.getCloseBtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                noticeDialogSure.dismiss();
                noticeContent = null;
            }
        });
    }


    private static final String TAG = "MainActivity";


    public static String lat = "";
    public static String lon = "";
    public static String city = "";
    private LocationUtil locationUtil;

    private void initLoc() {
        locationUtil = new LocationUtil(this);
        locationUtil.dingwei();
        locationUtil.setOnLocChangedListener(new LocationUtil.OnLocChangedListener() {
            @Override
            public void onLocationChanged(AMapLocation loc) {
                Log.i("城市：",loc.getCity());
                lat = loc.getLatitude()+"";
                lon = loc.getLongitude()+"";
                city = loc.getCity();
                SharedHelper.saveKeyValueForString(MainActivity.this,"lat",loc.getLatitude() + "");
                SharedHelper.saveKeyValueForString(MainActivity.this,"lat",loc.getLongitude() + "");
                SharedHelper.saveKeyValueForString(MainActivity.this,"city",loc.getCity());
                SharedHelper.saveKeyValueForString(MainActivity.this,"province",loc.getProvince()+ "");
                SharedHelper.saveKeyValueForString(MainActivity.this,"area",loc.getDistrict()+ "");

                locationUtil.stopLocation();
                locationUtil.destroyLocation();
            }
        });
    }

    private boolean needUpload = false;
    /**
     * 检测在线心跳包
     */
    private void heartConnect(){
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            if("此号冻结申诉联系客服".equals(baseBean.getMsg())){
                //推出登錄
                SharedHelper.clear(this);
                SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE);
                sp.edit().putBoolean("isFirst", true).apply();
                NimUIKit.logout();
                APP.getInstance().finishAllActivity();
                RxActivityTool.skipActivity(this,LoginActivity.class);
                RxToast.normal("此号冻结申诉联系客服");
                finish();
            }
        };
        Map<String, Object> params = new HashMap<>();//登录上传参数
        params.put("memberId", SharedHelper.readId(this));
        params.put("city",city);
        params.put("lat",lat);
        params.put("lng",lon);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().heartConnect(new ProgressSubscriber<>(onNextListener, this, false), requestBody);
    }


}
